/*
 *  This file is part of AtlasMapper server and clients.
 *
 *  Copyright (C) 2012 Australian Institute of Marine Science
 *
 *  Contact: Gael Lafond <g.lafond@aims.org.au>
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package au.gov.aims.metadatagenerator.exporter;

import au.gov.aims.metadatagenerator.entity.Project;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.tools.ToolManager;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;

public class NERPProjectExporter extends Exporter<Project> {
	private static final Logger LOGGER = Logger.getLogger(NERPProjectExporter.class.getName());
	private static final SimpleDateFormat DATESTAMP_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

	@Override
	public void exportToFile(Project project, File outputFile) throws IOException {
		Velocity.init();

		if (project.getUUID() == null) {
			// Generate a random UUID
			project.setUUID(UUID.randomUUID().toString());
		}

		VelocityContext context = this.getTemplateContext(project);

		InputStream inputStream = null;
		Reader reader = null;
		Writer writer = null;
		try {
			inputStream = NERPProjectExporter.class.getClassLoader().getResourceAsStream("NERPProjectTemplate.xml");
			reader = new InputStreamReader(inputStream);
			writer = new FileWriter(outputFile);
			Velocity.evaluate(context, writer, "NERP Project template", reader);
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch(Exception ex) {
					LOGGER.log(Level.WARNING, "Can not close the template input stream", ex);
				}
			}
			if (reader != null) {
				try {
					reader.close();
				} catch(Exception ex) {
					LOGGER.log(Level.WARNING, "Can not close the template reader", ex);
				}
			}
			if (writer != null) {
				try {
					writer.close();
				} catch(Exception ex) {
					LOGGER.log(Level.WARNING, "Can not close the template writer", ex);
				}
			}
		}
	}

	private VelocityContext getTemplateContext(Project project) {
		ToolManager velocityToolManager = new ToolManager();
		velocityToolManager.configure("velocity-tools.xml");
		VelocityContext context = new VelocityContext(velocityToolManager.createContext());

		context.put("project", project);
		context.put("dateStamp", DATESTAMP_FORMAT.format(new Date()));
		// A new generator per XML document; the IDs has to be unique in the XML document, but they can be found in other XML documents.
		context.put("xsdIdGenerator", new XsdIdGenerator());

		return context;
	}
}
